package com.campol.utils;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlUtils {

	public static Node getChildNode(Element element, String name) {
		NodeList elements = element.getElementsByTagName(name);
		return (elements.getLength() == 0 ? null : elements.item(0));
	}

	public static Node getChildNode(Node node, String name) {
		NodeList nodes = node.getChildNodes();

		int nodesCount = nodes.getLength();
		for (int i = 0; i < nodesCount; i++) {
			Node child = nodes.item(i);
			if (child.getNodeName().equals(name)) return child;
		}

		return null;
	}

	public static String getNodeValue(Node node) {
		if (node == null) return null;
		Node child = node.getFirstChild();
		return child == null ? null : child.getNodeValue();		
	}

	public static String getChildNodeTextContent(Node node, String name, boolean fixString) {
		Node child = getChildNode(node, name);
		if (child == null) return null;

		//TODO: check this code
		String textContent = "";
		if (child.getFirstChild() != null) {
			 textContent = child.getFirstChild().getNodeValue();
		}
		return fixString ? trimString(textContent) : textContent;
	}

	public static String trimString(String textContent) {
		int startIndex = 0;
		while (startIndex < textContent.length() && (textContent.charAt(startIndex) == '\n' || textContent.charAt(startIndex) == ' ')) {
			startIndex++;
		}

		int endIndex = textContent.length() - 1;
		while (endIndex >= startIndex && (textContent.charAt(endIndex) == '\n' || textContent.charAt(endIndex) == ' ')) {
			endIndex--;
		}

		if (startIndex == endIndex) return null;
		return String.copyValueOf(textContent.toCharArray(), startIndex, endIndex - startIndex + 1);
	}
}
